package com.omega.framework.common.validate.template;

import com.omega.framework.common.exception.ServiceException;
import com.omega.framework.common.model.BaseResponseCode;
import com.omega.framework.common.validate.annotation.NotBlank;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 字符串不为空校验
 *
 * @author Lv.
 * @date 2023/8/18 10:52
 */
@Component
public class StringNotBlankInvoke implements DataTypeValidate {

    /**
     * 空校验
     *
     * @param field  属性字段
     * @param object 类型值
     * @throws IllegalAccessException
     */
    @Override
    public void validateInvoke(Field field, Object object) throws IllegalAccessException {
        NotBlank notBlank = field.getAnnotation(NotBlank.class);
        if (notBlank != null && notBlank.enable()) {
            field.setAccessible(true);
            String value = (String) field.get(object);
            if (StringUtils.isBlank(value)) {
                if (StringUtils.isNotBlank(notBlank.message())) {
                    throw new ServiceException(BaseResponseCode.ONLY_THROW_MSG, notBlank.message());
                }
                throw new ServiceException(BaseResponseCode.ONLY_THROW_MSG, field.getName() + "不能为空");
            }
        }
    }
}
